"""
请求统一封装
'Content-Type': 'multipart/form-data; boundary=5c547cd2660245e5987545b1a7dfce35'

"""

import re

import allure
import  requests
from requests_toolbelt import MultipartEncoder

from tools.handle_path import image_dir
from tools.handle_response import HandleResponse
from tools.handle_global_data import HandleGlobalData
from conf.setting import host_info

class HandleRequests:
    """
    接口类型：普通接口，文件上传

    """
    def __init__(self):
        self.header ={"locale": "zh_CN"}
        self.handle_response = HandleResponse()
        # self.session = requests.session()  session鉴权


    #url地址拼接，url参数替换
    def __handle_url(self,url:str,port):
        try:
            #http: + 域名 + 端口 + 接口地址  == http://mall.lemonban.com:8107/login
            #处理url地址拼接问题
            if url.startswith("http") or url.startswith("https"):
                print("不用拼接url地址,写了全路径",)
            else:
                url = host_info["host"]+str(port)+url
            #替换url地址中需要替换的数据
            key_list = re.findall("#(\w.+?)#",url)
            if len(key_list)>0:
                for key in key_list:
                    if hasattr(HandleGlobalData,key):
                        url = url.replace(f"#{key}#",getattr(HandleGlobalData,key))
                    else:
                        print(key,"不在全局变量中，无法替换到url")
            else:
                print("url地址不需要替换参数")
        except Exception as e:
            print("执行报错了")
        finally:
            return url

    #鉴权处理
    def __handle_headers(self):
        #判断全局变量中是否有access_token这个属性，如果有这个属性，说明接下来的接口需要鉴权
        if hasattr(HandleGlobalData,"access_token"):
            token = getattr(HandleGlobalData,"access_token")
            self.header["Authorization"] = f"bearer{token}"
        else:
            print("全局变量中没有access_token属性，不需要鉴权")

    #单独处理图片上传的请求
    def __upload_image(self,url):
        try:
            with open(file=image_dir,mode="rb") as file:
                image = file.read()
                data = MultipartEncoder(
                    fields={
                        "file": ("py51.png", image, "image/png")
                    }
                )
                # Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8rqAL9mpzX4pNvqq
                self.header["Content-Type"] = data.content_type
                # 图片上传
                resp = requests.post(url=url, data=data, headers=self.header)
                return resp
        except Exception as e:
            print("执行报错了")
        finally:
            #修改Content-Type为application/json
            self.header["Content-Type"] = "application/json;charset=UTF-8"

    #请求发送
    @allure.step("发送请求")
    def send_request(self,method,url,port,is_upload,json_data=None):
        #替换url地址
        url = self.__handle_url(url=url,port=port)
        #鉴权处理
        self.__handle_headers()
        if is_upload == 1:
            #请求文件上传接口
            print("====图片上传接口发请求====")
            resp = self.__upload_image(url=url)
        else:
            #请求普通接口
            print("====普通接口发请求====")
            resp = requests.request(method=method,url=url,json=json_data,headers=self.header)
        resp = self.handle_response.handle_response(response=resp)
        return resp